package com.terabits.smartriver.controller;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by zzk on 2020/1/16 0016
 */
public class SellTicket implements Runnable {
    // 定义票
    private int tickets = 100;
    // Object obj = new Object();

    // Jdk5.0以后,java提供了一个具体的锁: 接口:Lock
    private Lock lock = new ReentrantLock(); //显示获取锁的前提,一定要创建Lock接口对象

    @Override
    public void run() {
        while (true) {
            try { //try...finally
                lock.lock(); // 获取锁    syncrhonized(obj)
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票");
                }

            } finally {//释放锁
                if (lock != null) {
                    lock.unlock();
                }
            }
        }
    }
}
